package com.jsgt.greekfire.ui.home.exchange

import android.text.*
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.NetworkUtil
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.ZERO_COMPARE
import com.jsgt.greekfire.bean.AssetsBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.viewmodel.CoinViewModel
import kotlinx.android.synthetic.main.activity_exchange.*
import org.greenrobot.eventbus.EventBus
import java.math.BigDecimal
import java.util.*

/**
 * 兑换
 * author fhx
 * create time 2020/4/30 16:11
 **/
class ExchangeActivity : BaseActivity() {
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }
    private var pwdDialog: SecurityPwdDialog? = null

    override fun getLayoutId(): Int = R.layout.activity_exchange

    //    val dotNumber = 0
    val dotNumber1 = 4
    lateinit var usedBean: AssetsBean
    override fun main() {
        usedBean = NetDataManager.findAssetsBean("2")!!
        title = getString(R.string.exchange)
//        num_et.numberDot = dotNumber
        all_num_tv.setOnClickListener {
            num_et.setText(PriceFormatUtil.format(usedBean!!.assetBalance!!, dotNumber1))
        }
        valid_sum_tv.text =
            "当前USDT余额 ${PriceFormatUtil.format(usedBean!!.assetBalance!!, dotNumber1)}"
        txv_hint.text =
            Html.fromHtml("<font color='#ffffff'>GFC1枚</font> 兑换价格为 <font color='#ffffff'>0.2USDT</font>")
        NetDataManager.getUserAssets()

        num_et.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(s)) {
                    val balance = PriceFormatUtil.format(usedBean!!.assetBalance!!, 0)
                    if (s.toString().toDouble() > balance.toDouble()) {
                        num_et.setText(balance)
                        manage_coin_num_tv.text =
                            "${BigDecimal(balance).multiply(BigDecimal("5"))}"
                        endSelection(num_et)
                    } else {
                        manage_coin_num_tv.text =
                            "${BigDecimal(s.toString()).multiply(BigDecimal("5"))}"
                    }
                } else {
                    manage_coin_num_tv.text = ""
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        submit_tv.setOnClickListener {
            if (isFastClick()){
                return@setOnClickListener
            }
            if (NetworkUtil.isNetworkAvailable()) {
                val num = num_et.text.toString().trim()
                var gfcNum = 0
                if (TextUtils.isEmpty(num)) {
                    ToastUtils.show(this, "请输入USDT数量")
                } else {
                    gfcNum = num.toInt() * 5
                    if (num.toDouble() < ZERO_COMPARE) {
                        ToastUtils.show(this, "数量必须大于0")
                    } else {
                        when {
                            BigDecimal(num).compareTo(BigDecimal(usedBean.assetBalance!!)) == 1 -> {
                                ToastUtils.show(this, "余额不足")
                            }
                            gfcNum < 100 -> {
                                ToastUtils.show(this, "最低兑换100枚GFC")
                            }
                            gfcNum > 1000 -> {
                                ToastUtils.show(this, "最多兑换1000枚GFC")
                            }
                            gfcNum % 100 != 0 -> {
                                ToastUtils.show(this, "GFC的数量须为100的倍数")
                            }
                            else -> {
                                initDialog()
                                pwdDialog?.numberTv?.text = num
                                pwdDialog?.show()
                            }
                        }
                    }
                }
            } else {
                ToastUtils.showNetUnAvailableToast()
            }

        }
        coinViewModel.exchangeLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(this, "兑换成功")
            EventBus.getDefault().post(TransferEvent(num_et.text.toString()))
            pwdDialog?.dismiss()
            finish()
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
    }

    /**
     * 设置EditText游标至末尾
     */
    private fun endSelection(editText: EditText) {
        val text: CharSequence = editText.text
        if (text is Spannable) {
            val spanText: Spannable = text as Spannable
            Selection.setSelection(spanText, text.length)
        }
    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(this, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                val num = num_et.text.toString().trim()
                showProgress(true)
                coinViewModel.u2GFC(
                    num,
                    "${BigDecimal(num).multiply(BigDecimal("5"))}",
                    result
                )
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }
}